package handlers

import(
	"net/http"
	"encoding/json"
	"werewolf/core"
)

func VoteHandler(w http.ResponseWriter, r *http.Request) {         //  统计投票结果

	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	RmNo := r.URL.Query().Get("room")

	handle, err := core.Connection()
	if err!= nil {
		http.Error(w, "Error connecting to database" + err.Error(), http.StatusInternalServerError)
		return
	}
	defer handle.Close()

	tx, err := handle.Begin()
	if err!= nil {
		http.Error(w, "Error starting transaction" + err.Error(), http.StatusInternalServerError)
		return
	}
	defer tx.Commit()

	var playNo int
	err = tx.QueryRow("SELECT PlayerNo FROM game WHERE RmNo = ?", RmNo).Scan(&playNo)
	if err!= nil {
		http.Error(w, "Error getting player number" + err.Error(), http.StatusInternalServerError)
		return
	}

	var all_votes []int
	count := 0
	rows, err:= tx.Query("SELECT Vote, count(*) as frequency FROM Player WHERE RmNo = ? GROUP BY Vote HAVING frequency = (SELECT MAX(frequency) FROM (SELECT count(*) as frequency FROM Player WHERE RmNo = ? AND Vote <> 0 GROUP BY Vote) as max_freq)", RmNo, RmNo)
	if err!= nil {
		http.Error(w, "Error getting vote count" + err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	for rows.Next() {
		var vote int
		err = rows.Scan(&vote, &count)
		if err!= nil {
			http.Error(w, "Error scanning vote count" + err.Error(), http.StatusInternalServerError)
			return
		}
		if vote !=0 {
			all_votes = append(all_votes, vote)
		}
	}
	
	var response struct {
		Result string
		Votes []int
	}


	if len(all_votes) == 1 {
		response.Result = "success"
		response.Votes = all_votes

		_, err = tx.Exec("UPDATE player SET Survival = 0 WHERE RmNo = ? AND No = ?", RmNo, all_votes[0])
		if err!= nil {
			http.Error(w, "Error updating survival" + err.Error(), http.StatusInternalServerError)
			return
		}
		
	}else{
		response.Result = "revote"
		response.Votes = all_votes
	}
	json.NewEncoder(w).Encode(response)


}